package net.expectx.pay.merchant.tag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

/**
 * @author lijian
 */
public class ZtreeTag extends TagSupport {
    private static final Integer INTEGER_TWO=2;
    private static final String DEFAULT_STYLE="zTreeStyle";
    /**
     * Ztree组件ID
     * 必填
     */
    private String pickerId;
    private String initKey;
    private String server;
    private String style;
    private Integer width;
    private Boolean required;
    /**
     * 默认值
     * 选填
     */
    private String defaultVal;
    @Override
    public int doEndTag() throws JspException {

        HttpServletRequest request=(HttpServletRequest) this.pageContext.getRequest();
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        StringBuffer buffer=new StringBuffer();
        String stylePath=(null==style)?(DEFAULT_STYLE+"/"+DEFAULT_STYLE+".css"):(style+"/"+style+".css");
        buffer.append("<link rel=\"stylesheet\" href=\""+basePath+"resources/css/"+stylePath+"\" media=\"all\">\n" );
        buffer.append("<script src=\""+basePath+"resources/js/jquery-1.4.4.min.js\"></script>\n" );
        buffer.append("<script src=\""+basePath+"resources/js/jquery.ztree.all.js\"></script>");
        buffer.append("<div class=\"layui-input-inline\">\n" );
        String value="";
        String text="";
        if (null != defaultVal) {
            if (defaultVal.split(":").length>=INTEGER_TWO){
                value=defaultVal.split(":")[0];
                text=defaultVal.split(":")[1];
            }else{
                value=defaultVal;
            }
        }
        buffer.append("<input type=\"hidden\"  value='"+value+"'  name=\""+pickerId+"\" id=\""+pickerId+"\">\n");
        String treeName=pickerId+"Tree";
        required = (null == required ? true : required);
        String requiredS="";
        if (required){
            requiredS="lay-verify=\"required\"";
        }
        buffer.append("<input type=\"text\"   placeholder=\"请选择\" id=\""+treeName+"\" value=\""+text+"\" style=\"width:"+width+"px\" onfocus=\""+pickerId+"ShowMenu()\" name=\""+treeName+"\" "+requiredS+" placeholder=\"\" readonly autocomplete=\"off\" class=\"layui-input\">\n" );
        buffer.append( "</div>");

        buffer.append("<div id=\""+pickerId+"MenuContent\" class=\"menuContent\" style=\"display:none; position: absolute;background-color: #fff;z-index: 999;    height: 400px;overflow-y: scroll;\">\n");
        buffer.append("<ul id=\""+pickerId+"TreeList\" class=\"ztree\" style=\"margin-top:0; width:160px;\"></ul>\n");
        buffer.append("</div>");
        buffer.append(script(treeName,basePath));
        JspWriter out=this.pageContext.getOut();
        try {
            out.println(buffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.doEndTag();

    }
    public String script(String treeName,String basePath){
        StringBuffer buffer=new StringBuffer();
        buffer.append("<SCRIPT type=\"text/javascript\">\n" +
                "            var "+pickerId+"Setting = {\n" +
                "                view: {\n" +
                "                    dblClickExpand: false\n" +
                "                },\n" +
                "                data: {\n" +
                "                    simpleData: {\n" +
                "                        enable: true\n" +
                "                    }\n" +
                "                },\n" +
                "                callback: {\n" +
                "                    beforeClick: "+pickerId+"BeforeClick,\n" +
                "                    onClick: "+pickerId+"OnClick\n" +
                "                },\n" +
                "                async:{\n" +
                "                    enable:true,\n" +
                "                    url:\""+basePath+server+"\",\n" +
                "                    type:\"GET\",\n" +
                "                    autoParam:[\"id\"]\n" +
                "                }\n" +
                "            };\n" +
                "            var "+pickerId+"Nodes =[];\n" +
                "            $.ajax({\n" +
                "                type:\"GET\",\n" +
                "                url:\""+basePath+server+"\",\n" +
                "                async:false,\n" +
                "                data:{id:"+(null==initKey?0:initKey)+"},\n" +
                "                dataType:\"JSON\",\n" +
                "                success:function (data) {\n" +
                "                    var jsonArray=jQuery.parseJSON(data);\n" +
                "                    if (jsonArray.length>0){\n" +
                "                        for (var i=0;i<jsonArray.length;i++){\n" +
                "                            "+pickerId+"Nodes.push(jsonArray[i])\n" +
                "                        }\n" +
                "                    }\n" +
                "                }\n" +
                "            })\n" +
                "            function "+pickerId+"BeforeClick(treeId, treeNode) {\n" +
                "            }\n" +
                "            function "+pickerId+"OnClick(e, treeId, treeNode) {\n" +
                "                var zTree = $.fn.zTree.getZTreeObj(\""+pickerId+"TreeList\");\n" +
                "                var nodes = zTree.getSelectedNodes();\n" +
                "                var name = \"\";\n" +
                "                var id=\"\";\n" +
                "                nodes.sort(function compare(a,b){return a.id-b.id;});\n" +
                "                for (var i=0, l=nodes.length; i<l; i++) {\n" +
                "                    name += nodes[i].name + \",\";\n" +
                "                    id += nodes[i].id + \",\";\n" +
                "                }\n" +
                "                if (name.length > 0 ) name = name.substring(0, name.length-1);\n" +
                "                if (id.length > 0 ) id = id.substring(0, id.length-1);\n" +
                "                $(\"#"+treeName+"\").val(name);\n" +
                "                $(\"#"+pickerId+"\").val(id);\n" +
                "                "+pickerId+"HideMenu();\n" +
                "                console.log(id,name)\n" +
                "            }\n" +
                "            function "+pickerId+"ShowMenu() {\n" +
                "                var cityObj = $(\"#"+treeName+"\");\n" +
                "                var cityOffset = $(\"#"+treeName+"\").offset();\n" +
                "                $(\"#"+pickerId+"MenuContent\").css({width:$(\"#"+treeName+"\").css(\"width\"),left:(cityOffset.left-20) + \"px\", top:cityOffset.top + cityObj.outerHeight() + \"px\"}).slideDown(\"fast\");\n" +
                "                $(\"body\").bind(\"mousedown\", "+pickerId+"OnBodyDown);\n" +
                "            }\n" +
                "            function "+pickerId+"HideMenu() {\n" +
                "                $(\"#"+pickerId+"MenuContent\").fadeOut(\"fast\");\n" +
                "                $(\"body\").unbind(\"mousedown\", "+pickerId+"OnBodyDown);\n" +
                "            }\n" +
                "            function "+pickerId+"OnBodyDown(event) {\n" +
                "                if (!(event.target.id == \"menuBtn\" || event.target.id == \""+pickerId+"MenuContent\" || $(event.target).parents(\"#"+pickerId+"MenuContent\").length>0)) {\n" +
                "                    "+pickerId+"HideMenu();\n" +
                "                }\n" +
                "            }\n" +
                "            $(document).ready(function(){\n" +
                "                $.fn.zTree.init($(\"#"+pickerId+"TreeList\"), "+pickerId+"Setting, "+pickerId+"Nodes);\n" +
                "            });\n" +
                "        </SCRIPT>");
        return buffer.toString();
    }

    public String getPickerId() {
        return pickerId;
    }

    public void setPickerId(String pickerId) {
        this.pickerId = pickerId;
    }

    public String getStyle() {
        return style;
    }

    public void setStyle(String style) {
        this.style = style;
    }

    public String getInitKey() {
        return initKey;
    }

    public void setInitKey(String initKey) {
        this.initKey = initKey;
    }

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    public Boolean getRequired() {
        return required;
    }

    public void setRequired(Boolean required) {
        this.required = required;
    }

    public String getDefaultVal() {
        return defaultVal;
    }

    public void setDefaultVal(String defaultVal) {
        this.defaultVal = defaultVal;
    }
}
